package com.vitabuybuy.tv.ui.shopcenter

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cc.shinichi.library.ImagePreview
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.ext.mmkv
import com.library.common.toast.XToast
import com.library.common.util.MMKVContancts
import com.library.common.widget.RecycleViewDivider
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.databinding.ActivityGoodsDetailsBinding
import com.vitabuybuy.tv.dialog.SpecSelectorDialog
import com.vitabuybuy.tv.dialog.StoreCouponsPopup
import com.vitabuybuy.tv.dto.BannerDto
import com.vitabuybuy.tv.dto.OrderDetailDto
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.cart.ConfirmOrderActivity
import com.vitabuybuy.tv.ui.shopcenter.adapter.CommentListAdapter
import com.vitabuybuy.tv.ui.shopcenter.store.StoreHomeActivity
import com.vitabuybuy.tv.ui.shopcenter.viewmodel.GoodsDetailsViewModel
import com.vitabuybuy.tv.ui.tencent.chat.ChatActivity
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.RoomInfo
import com.vitabuybuy.tv.ui.tencent.liveroom.ui.AudienceLiveRoomActivity
import com.vitabuybuy.tv.ui.tencent.superplay.SuperPlayVidelMainActivity
import com.vitabuybuy.tv.utils.EventCode
import com.vitabuybuy.tv.utils.WebViewUtils
import kotlinx.android.synthetic.main.activity_goods_details.*

class GoodsDetailsActivity : BaseActivity<GoodsDetailsViewModel, ActivityGoodsDetailsBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.activity_goods_details

    private var scrollY = 0
    private var goodId: Int? = 0
    private val commentAdapter by lazy { CommentListAdapter(CommentListAdapter.NOT_DISPLAY_PIC_VIDEO) }
    private val specDialog by lazy { SpecSelectorDialog(mContext) }
    private val bannerlist = ArrayList<BannerDto.SlideListBean>()
    private lateinit var hasFavDrawable: Drawable
    private lateinit var noneFavDrawable: Drawable
    private var couponsPopup: StoreCouponsPopup? = null

    override fun onGetBundle(bundle: Bundle?) {
        goodId = bundle?.getInt("goodId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.viewModel = viewModel
        specDialog.setBottomBtn(SpecSelectorDialog.TYPE_BY_NOMAR_GOODS)
        initBanner()
        WebViewUtils.defaultSetting(rcvCommodityDetail)
        rlComment.apply {
            adapter = commentAdapter
            layoutManager = LinearLayoutManager(mContext)
            addItemDecoration(RecycleViewDivider(mContext, 1))
        }
        hasFavDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_shoucang)!!
        hasFavDrawable.setBounds(
            0,
            0,
            hasFavDrawable.minimumWidth,
            hasFavDrawable.minimumHeight
        )
        noneFavDrawable = ContextCompat.getDrawable(mContext, R.drawable.icon_tabbar_shoucang_n)!!
        noneFavDrawable.setBounds(
            0,
            0,
            noneFavDrawable.minimumWidth,
            noneFavDrawable.minimumHeight
        )
    }

    override fun observeData() {
        viewModel.apply {
            getDetails(goodId)
            getGoodsCommentList(goodId, false, 1, 3)
            getGoodsList(goodId)
            goodDetails.observe(this@GoodsDetailsActivity, Observer {
                for (str in it.images.split(";")) {
                    val bannerDto = BannerDto.SlideListBean()
                    bannerDto.image = str
                    bannerlist.add(bannerDto)
                }
                my_banner.setBannerData(bannerlist)
                rcvCommodityDetail.loadDataWithBaseURL(
                    null,
                    WebViewUtils.htmlContent(it.description),
                    "text/html",
                    "UTF-8",
                    null
                )
                if(!it.descriptionImages.isNullOrEmpty()){
                    descriptionlist.value = it.descriptionImages.split(";").toMutableList()
                }
                if (it.isFavorites) {
                    llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
                } else {
                    llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
                }
            })
            commentList.observe(this@GoodsDetailsActivity, Observer {
                commentAdapter.setNewData(it)
            })
            couponsList.observe(this@GoodsDetailsActivity, Observer {
                if (it.size == 0) {
                    XToast.normal(getString(R.string.this_store_has_no_coupons))
                    return@Observer
                }
                couponsPopup = StoreCouponsPopup(
                    mContext,
                    it,
                    StoreCouponsPopup.RECEIVER_COUPONS
                ) { it, position ->
                    saveACoupon(it.id, position)
                }
                couponsPopup!!.showPopupWindow()
            })
            liveDetils.observe(this@GoodsDetailsActivity, Observer {
                val roomInfo = RoomInfo().apply {
                    audienceCount = it.viewerQuantity
                    roomID = it.roomNumber
                    roomInfo = it.title
                    roomName = it.title
                    mixedPlayURL = it.playUrl
                    goodDetails.value?.store?.let {
                        roomCreator = it.id.toString()
                        authorName = it.name
                        authorId = it.id.toString()
                        authorAvatar = it.logo
                        isExecutor = false
                        attention = it.isAttention
                    }
                    authorRegion = goodDetails.value?.region?.name
                    liveId = it.id
                    userId = mmkv.decodeInt(MMKVContancts.USER_ID).toString()
                    userName = mmkv.decodeString(MMKVContancts.USER_NICKNAME)
                    createRoom = false
                }
                AudienceLiveRoomActivity.openActivity(mContext, roomInfo)
            })
        }
    }

    override fun eventHandling() {
        btnGoWatch.setOnClickListener {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnClickListener
            }
            viewModel.goodDetails.value?.let {
                if (it.isLive) {
                    viewModel.getLiveDetail(it.liveId)
                }
            }
        }
        scrollview.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
            this.scrollY = scrollY
            if (scrollY <= 0) {
                rl_title.setBackgroundColor(Color.argb(0, 255, 255, 255))
            } else {
                val scale = scrollY.toFloat() / rl_title!!.height
                val alpha = 255 * if (scale > 1) 1f else scale
                rl_title.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
            }
        })
        rlCheckComment.setOnClickListener {
            CommodityCommentActivity.openActivity(
                mContext,
                goodId
            )
        }
        iv_finish.setOnClickListener { finish() }

        onClick({
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@onClick
            }
            specDialog.setSpecDatas(
                viewModel.goodDetails.value!!.attributeList,
                viewModel.goodDetails.value!!.goodsList,
                viewModel.goodDetails.value!!.salePrice,
                if (bannerlist.isNotEmpty()) bannerlist[0].image else ""
            )
            specDialog.show()
        }, rlChoose, llAddToShoppingCart, llBuyNow)
        specDialog.onAddToCartClick = { goodId, buyNum ->
            viewModel.addToCart(goodId, buyNum)
        }
        specDialog.onbuyNowClick = { goodId, buyNum ->
            ConfirmOrderActivity.openActivity(
                mContext,
                goodId,
                buyNum,
                ConfirmOrderActivity.BUY_NOW
            )
        }
        btnAllCommodity.setOnClickListener {
            StoreHomeActivity.openActivity(
                mContext,
                viewModel.goodDetails.value?.store?.id,
                viewModel.goodDetails.value?.store?.name,
                StoreHomeActivity.JUMP_CATE_PAGE
            )
        }
        onClick({
            StoreHomeActivity.openActivity(
                mContext,
                viewModel.goodDetails.value?.store?.id,
                viewModel.goodDetails.value?.store?.name
            )
        }, btnEnterShop, llShop)

        llStar.setOnClickListener {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnClickListener
            }
            viewModel.collectOrcancel(
                viewModel.goodDetails.value!!.id,
                viewModel.goodDetails.value!!.isFavorites
            )
        }
        commentAdapter.onItemClick =
            { childPos: Int, images: ArrayList<OrderDetailDto.ItemListBean.VideoAndPicBean> ->
                if (images[childPos].tag == "video") {
                    SuperPlayVidelMainActivity.openActivity(
                        mContext,
                        images[childPos].fileUrl,
                        images[childPos].cover
                    )

                } else {
                    val previewImages = ArrayList<String>()
                    for (bean in images) {
                        if (bean.tag == "image") {
                            previewImages.add(bean.fileUrl)
                        }
                    }
                    ImagePreview.getInstance().setContext(mContext)
                        .setIndex(0)
                        .setShowDownButton(false)
                        .setImageList(previewImages)
                        .setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                        .setZoomTransitionDuration(300)
                        .setEnableDragClose(true)
                        .setErrorPlaceHolder(R.drawable.default_image).start()
                }
            }
        tvGetCoupons.setOnClickListener {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnClickListener
            }
            viewModel.getStoreCouponsList(viewModel.goodDetails.value?.store?.id)
        }
        mBinding.llCustomerService.setOnClickListener {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnClickListener
            }
            viewModel.goodDetails.value?.let { detal ->
                val goodsInfo = ChatInfo.GoodInfoBean().apply {
                    avatarUrl = mmkv.decodeString(MMKVContancts.USER_AVATAR, "")
                    version = 1
                    goodName = detal.name
                    price = String.format(getString(R.string.price_with_value),detal.salePrice)
                    thumbnail = if(bannerlist.isEmpty()) "" else bannerlist[0].image
                    googId = detal.id
                }
                val chatInfo = ChatInfo().apply {
                    type = TIMConversationType.C2C
                    id = detal.store.id.toString()
                    chatName = detal.store.name
                    goodInfoBean = goodsInfo
                }
                ChatActivity.openActivity(mContext, chatInfo)
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                viewModel.getDetails(goodId)
            }
            1 -> {
                XToast.success(getString(R.string.already_add_to_cart))
            }
            2 -> {
                viewModel.goodDetails.value!!.isFavorites = !(msg.obj as Boolean)
                if (viewModel.goodDetails.value!!.isFavorites) {
                    XToast.success(getString(R.string.already_success))
                    llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
                } else {
                    XToast.success(getString(R.string.cancel_collect))
                    llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
                }
            }
            3 -> {
                openActivity(mContext, msg.arg1)
            }
            4 -> {
                XToast.success(getString(R.string.already_save_coupon))
                couponsPopup!!.couponsAdapter.mData[msg.arg1].isReceived = true
                couponsPopup!!.couponsAdapter.notifyItemChanged(msg.arg1)
            }
        }
    }

    override fun onEvent(event: MessageEvent) {
        when (event.code) {
            EventCode.update_attantion -> {
                viewModel.goodDetails.value!!.isFavorites = event.message as Boolean
                if (viewModel.goodDetails.value!!.isFavorites) {
                    XToast.success(getString(R.string.already_success))
                    llStar.setCompoundDrawables(null, hasFavDrawable, null, null)
                } else {
                    XToast.success(getString(R.string.cancel_collect))
                    llStar.setCompoundDrawables(null, noneFavDrawable, null, null)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        my_banner.startAutoPlay()
    }

    override fun onPause() {
        super.onPause()
        my_banner.stopAutoPlay()
    }

    private fun initBanner() {
        my_banner.loadImage { _, model, view, _ ->
            ImageAdapter.setNomalImageUrl(
                view as ImageView,
                (model as BannerDto.SlideListBean).image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
    }


    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, goodId: Int) {
            mContext.startActivity(
                bundleOf(Pair("goodId", goodId)),
                GoodsDetailsActivity::class.java
            )
        }
    }
}
